<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\common\Pay;
use app\model\User;
use app\model\Vip;
use app\model\VipOrders;
use app\tool\Random;
use think\facade\Db;
use think\Request;

class VipController extends BaseController
{
	function index()
	{
		$user = User::findOrFail($this->user_id);
		if ($user->level == 1){
			$ids = [1];
		}
		if ($user->level == 2){
			$ids = [];
		}
		if ($user->level == 3){
			$ids = [2,3];
		}
		if ($user->level == 4){
			$ids = [3];
		}
		if ($user->level == 5){
			$ids = [];
		}
		$rows = Vip::whereIn('id',$ids)->select();
		$this->writeJson($rows);
    }
	
	
	function createOrder()
	{
		$vip_id =  $this->request->post('vip_id/d');
		$pay_type =  $this->request->post('pay_type/d');
		$row = Vip::findOrFail($vip_id);
		$user = User::findOrFail($this->user_id);
		
		$ordersn = Random::ordersn();
		$pay_amount = $row->price;
		// 启动事务
		Db::startTrans();
		try {
			$order = VipOrders::create([
				'user_id'=>$this->user_id,
				'vip_id'=>$row->id,
				'pay_amount'=>$pay_amount,
				'order_sn'=>$ordersn,
			]);
			$ret = Pay::pay($pay_type, $pay_amount, $ordersn, '购买会员', 'vip', $user->openid);
			// 提交事务
			Db::commit();
		} catch (\Exception $e) {
			// 回滚事务
			Db::rollback();
			$this->writeJson(0, $e->getMessage());
		}
		$this->writeJson($ret);
	}
	
	
	
}
